package com.tony.blog.server.common;

import cn.hutool.core.lang.Snowflake;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.tony.blog.api.utils.UpYunUtils;
import com.tony.blog.model.entity.SysModule;
import com.upyun.Result;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @Title: commonService
 * @Auther: 皮蛋布丁
 * @Date: 2021/08/21/22:02
 * @Description:
 */
@Service
public class CommonService {

    private static final Logger log = LoggerFactory.getLogger(CommonService.class);

    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd");

    private static final Snowflake SNOWFLAKE = new Snowflake(3,2);

    @Autowired
    private Environment env;

    /**
    * @Description: uploadLocal 上传文件(nio方式)
    * @Param: [multipartFile, sysModule, rootFolder 云储存根目录]
    * @return: java.util.Map<java.lang.String,java.lang.Object>
    * @Author: 皮蛋布丁
    * @Date: 2021/8/21 22:20
    */
    public Map<String,Object> uploadV2(MultipartFile multipartFile, final SysModule sysModule,String rootFolder) throws Exception {
        Map<String,Object> resMap = Maps.newHashMap();

        //TODO:将前端上传过来的文件保存到指定的服务器目录下
        String fileName = multipartFile.getOriginalFilename();
        Long size = multipartFile.getSize();
        //1.jpg -> .jpg
        String suffix = StringUtils.substring(fileName,StringUtils.indexOf(fileName,"."));

        //图片命名方式一：时间戳
        //String newFileName = System.nanoTime() + suffix;

        //图片命名方式二：雪花算法
        String newFileName = SNOWFLAKE.nextIdStr() + suffix;
        String filePath = DATE_FORMAT.format(new Date()) + "/" + sysModule.getCode() + "/" + newFileName;

        //region 文件上传至云端
        byte[] byteArr = multipartFile.getBytes();
        Result upYunData = UpYunUtils.byteSync(byteArr,rootFolder + filePath);
        JSONObject photoMsg = JSONObject.parseObject(upYunData.getMsg());
        String yunFile = env.getProperty("common.user.img.root.url") + photoMsg.getString("url");
        //endregion

        //region 文件上传至本地目标地址
        String newFile = env.getProperty("common.file.local.root.url") + filePath;

        File file = new File(newFile);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        //获取路径地址
        Path path = Paths.get(newFile);

        //TODO:如果文件名相同，则覆盖(复制图片)
        Files.copy(multipartFile.getInputStream(),path, StandardCopyOption.REPLACE_EXISTING);
        //删除本地文件
        Files.delete(path);
        //endregion

        //TODO:保存成功后将可以被访问的url拿出来，然后添加到数据库中，用于记录上传历史
        resMap.put("fileUrl",filePath);
        resMap.put("fileName",fileName);
        resMap.put("size",size.toString());
        resMap.put("suffix",suffix);
        return resMap;
    }



}
